package com.scau.ums.service.imp.repair;

import com.scau.ums.mapper.*;
import com.scau.ums.model.*;
import com.scau.ums.service.TaskOrder;
import com.scau.ums.service.imp.info.DefaultSendInfoImp;
import com.scau.ums.util.tools.RepairReportTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.List;

/**
 * author: 莫伟杰
 * date： 2019/8/1 17:03
 */

@Service
public class ManualTaskOrder implements TaskOrder {

    private MaintainerMapper maintainerMapper;
    private MaintaingroupMapper groupMapper;
    private RepairreportMapper reportMapper;
    private RepairtaskorderMapper taskMapper;
    private SelectTaskMapper selectTaskMapper;
    private DataSourceTransactionManager transactionManager;
    private DefaultSendInfoImp sendInfoImp;

    @Autowired
    public ManualTaskOrder(MaintainerMapper maintainerMapper, MaintaingroupMapper groupMapper, RepairreportMapper reportMapper,
                           RepairtaskorderMapper taskMapper,DataSourceTransactionManager transactionManager,DefaultSendInfoImp sendInfoImp,
                           SelectTaskMapper selectTaskMapper) {
        this.maintainerMapper = maintainerMapper;
        this.groupMapper = groupMapper;
        this.reportMapper = reportMapper;
        this.taskMapper = taskMapper;
        this.transactionManager = transactionManager;
        this.sendInfoImp = sendInfoImp;
        this.selectTaskMapper = selectTaskMapper;
    }
    @Override
    public List<Maintainer> getMaintainersByGroup(String group) {
        //获取组名称对应的组ID
        MaintaingroupExample maintaingroupExample = new MaintaingroupExample();
        maintaingroupExample.createCriteria().andNameEqualTo(group);
        List<Maintaingroup> groupList = groupMapper.selectByExample(maintaingroupExample);
        if(groupList.size()==0) return null;
        int groupId = groupList.get(0).getId();
        //查询
        MaintainerExample maintainerExample = new MaintainerExample();
        maintainerExample.createCriteria().andMaintainergroupEqualTo(groupId);
        return maintainerMapper.selectByExample(maintainerExample);
    }

    @Override
    public List<Maintainer> getMaintainersByGroupId(Integer groupId)
    {
        MaintainerExample maintainerExample = new MaintainerExample();
        maintainerExample.createCriteria().andMaintainergroupEqualTo(groupId);
        return maintainerMapper.selectByExample(maintainerExample);
    }

    @Override
    public boolean orderTaskToMaintain(String maintainerId, int repairReportId) {
        Maintainer maintainer = maintainerMapper.selectByPrimaryKey(maintainerId);
        if(maintainer==null) return false;
        Repairreport report = reportMapper.selectByPrimaryKey(repairReportId);
        if(report==null) return false;
        //维修报单进入下一阶段
        report.setState(report.getState()+1);
        //维修工未完成任务数量+1
        maintainer.setUnfinishedtasks(maintainer.getUnfinishedtasks()+1);
        Repairtaskorder taskOrder = new Repairtaskorder();
        taskOrder.setId(0);
        taskOrder.setReportid(report.getId());
        taskOrder.setMaintainerid(maintainer.getId());
        taskOrder.setMaintainername(maintainer.getName());
        taskOrder.setMaintaingroup(maintainer.getMaintainergroup());
        //事务管理
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        try
        {
            taskMapper.insert(taskOrder);
            reportMapper.updateByPrimaryKey(report);
        }
        catch (Exception e) {
            transactionManager.rollback(status);
            e.printStackTrace();
            return false;
        }
        transactionManager.commit(status);
        //发消息
        String content = "高校后勤综合管理平台：\n您有一个新维修任务。"+report.getDormregion()+report.getDormbuilding()+"栋"+
                report.getDormroom()+" 联系人："+report.getReportername()+report.getTelephone()+" 维修类型："+RepairReportTool.returnRepairType(report.getType());
        sendInfoImp.sendInfo(sendInfoImp.createInfo("新维修任务","system",maintainerId,
                User.userTypeToChinese(User.MAINTAINER),content));
        String contentToStudent = "高校后勤综合管理平台：\n您的报修申请已派工，维修员："+maintainer.getId()+" "+maintainer.getName()
                +" "+maintainer.getTelephone()+"。请保持手机畅通，并留意核对上门维修员的信息。";
        sendInfoImp.sendInfo(sendInfoImp.createInfo("报修申请派工","system",report.getReporterid(),User.userTypeToChinese(User.STUDENT),contentToStudent));
        return true;
    }

    @Override
    public boolean cancelTaskByTaskOrderId(Integer taskOrderId) {
        Repairtaskorder taskOrder = taskMapper.selectByPrimaryKey(taskOrderId);
        if(taskOrder==null) return false;
        Repairreport report = reportMapper.selectByPrimaryKey(taskOrder.getReportid());
        Maintainer maintainer = maintainerMapper.selectByPrimaryKey(taskOrder.getMaintainerid());
        report.setState(report.getState()-1);//状态回退
        maintainer.setUnfinishedtasks(maintainer.getUnfinishedtasks()-1);
        //事务管理
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        try
        {
            taskMapper.deleteByPrimaryKey(taskOrder.getId());
            reportMapper.updateByPrimaryKey(report);
            maintainerMapper.updateByPrimaryKey(maintainer);
            transactionManager.commit(status);
            return true;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            transactionManager.rollback(status);
            return false;
        }
    }

    @Override
    public List<Repairtaskorder> getAllCanCancelTasks() {
        return selectTaskMapper.allowCancelTaskList();
    }
}
